# 读取数据集的模块
import sqlite3
import sys

from src.go import Go
from ai.data_center import Data_Center
import src.global_config as gl
import configparser
import os
import json


def combine(data: str):
    line = data.split('\n')

    temp = ''
    for i in range(len(line)):
        temp = temp + line[i]

    return temp


def save(file, need):
    # 先检查这个文件是否有被读取过
    select = data_center.check_file_name(file)
    select = select[0]
    if int(select['count']) != 0:
        print("该文件=[{}]已被解析过".format(file))
        data_center.vacuum()
        if need is True:
            return
        exit(0)
    else:
        print("正在解析", file)
    go = Go()
    fs = open(file, encoding='UTF-8')
    line = None
    try:
        line = fs.read()
    except UnicodeDecodeError:
        print("文件编码错误")
        return
    if need is True:
        line = combine(line)
    line = line.split('\n')
    if len(argv) > 3:
        print("大概有{}行数据".format(len(line)))
        exit(0)
    for i in range(len(line)):
        print("正在处理->", i)
        sgf = line[i]
        if len(sgf) < 10:
            continue
        additional = go.parse_additional_sgf(sgf)

        # print("parsed = {}\nadditional = {}".format(parsed, additional))
        try:
            data_center.save_goban(sgf, additional)
        except sqlite3.IntegrityError:
            print("主键冲突 棋谱已经存在")
        except sqlite3.OperationalError:
            print("出现错误")

    print("文件解析完毕 保存解析记录..")

    data_center.save_checked_name(file)


# 配置文件地址
filename = './config.ini'
# 读取程序配置
config = configparser.ConfigParser()
config.read(filename)
port = config['tcp']['port']

# 设置全局变量
dbpath = os.path.dirname(os.path.realpath(__file__))
gl.set_value('logpath', dbpath)
dbpath = os.path.join(dbpath, config['db']['filepath'])
gl.set_value('dbpath', dbpath)
gl.set_value('config', config)

# 获取文件名
argv = sys.argv
file = argv[1]

data_center = Data_Center()
data_center.init()
# 判断删除逻辑
if file == 'del' or file == 'delete':
    confirm = input("即将删除所有围棋训练数据 输入[confirm]以确认:\n")
    if confirm == 'confirm':
        data_center.delete_go_data()
        print("删除了所有数据")
    else:
        print("取消删除")
    exit(0)
elif file == 'count':
    # 获取一共多少条记录
    count1 = data_center.count_go_data()
    count1 = count1[0]
    print("目前数据库已有{}个棋谱".format(count1['count']))
    exit(0)
dis = None
try:
    dirs = os.listdir(file)
    for single in range(len(dirs)):
        dirs[single] = file + "/" + dirs[single]
        save(dirs[single], True)
except NotADirectoryError:
    print("检测到文件")
    save(file, False)

print("程序处理完毕")
data_center.vacuum()
